<?php
/**
 * Created by PhpStorm.
 * User: ����
 * Date: 2015/11/24
 * Time: 19:11
 */

namespace app\common\utils;

use app\models\GkyQyhMenu;
use Closure;
use Overtrue\Wechat\MenuItem;
use app\models\GkyQyh;

class QyhServer
{
    const API_MENU_CREATE = 'https://qyapi.weixin.qq.com/cgi-bin/menu/create';
    const API_MENU_GET    = 'https://qyapi.weixin.qq.com/cgi-bin/menu/get';
    const API_MENU_DELETE = 'https://qyapi.weixin.qq.com/cgi-bin/menu/delete';

    const API_APP_SET     = 'https://qyapi.weixin.qq.com/cgi-bin/agent/set';
    const API_APP_LIST     = 'https://qyapi.weixin.qq.com/cgi-bin/agent/list';

    /**
     * @var GkyQyh $gkyQyh
     */
    public $gkyQyh;

    public function __construct($gkyQyh){

        $this->gkyQyh = $gkyQyh;
    }

    /**
     * 设置菜单
     *
     * @return mixed
     * @throws \Overtrue\Wechat\Exception
     */
    public function setMenu($appid,$agentid){

        $menus = GkyQyhMenu::find()
            ->orderBy(['sort'=>SORT_ASC])
            ->where(['app_id' => $appid,'pid'=>0])
            ->all();

        $results = array();
        foreach($menus as $menu){

            if(count($menu->subs) == 0){
                $item = [
                    'name' => $menu->name,
                    'type' => $menu->menuType->key,
                    'key'  => $menu->key,
                    'url'  => $menu->url
                ];
            }else{
                $item = [
                    'name' => $menu->name,
                ];
            }
            $subArray = array();
            foreach($menu->subs as $sub){

                $subBtn = [
                    'name' => $sub->name,
                    'type' => $sub->menuType->key,
                    'key'  => $sub->key,
                    'url'  => $sub->url
                ];

                $subArray[] = $subBtn;
            }
            $item['sub_button'] = $subArray;
            $results['button'][] = $item;
        }

        return HttpClient::post(
            self::API_MENU_CREATE.'?access_token='.$this->gkyQyh->getToken().'&agentid='.$agentid,
            json_encode($results, JSON_UNESCAPED_UNICODE)
        );
    }

    /**
     * 获取所有企业应用
     */
    public function getApps(){

        $url = self::API_APP_LIST.'?access_token='.$this->gkyQyh->getToken();
        return HttpClient::get($url);
    }

    /**
     * 设置企业应用
     */
    public function setApp($app){

        $params = [
            "agentid" => $app->id,
            "report_location_flag"=> $app->report_location_flag,
            "logo_mediaid" => $app->logo_mediaid,
            "name" => $app->name,
            "description" => $app->description,
            "redirect_domain" => $app->redirect_domain,
            "isreportuser" => $app->isreportuser,
            "isreportenter" => $app->isreportenter
        ];

        $url = self::API_APP_SET.'?access_token='.$this->gkyQyh->getToken();
        return HttpClient::post($url, $params);

    }

}